package com.qufadai.framework.orm.jdbc;

import java.lang.reflect.Method;

public class ReflectParser {
	public final static int INT = 1;
	public final static int LONG = 2;
	public final static int FLOAT = 3;
	public final static int DOUBLE = 4;
	public final static int STRING = 5;
	public final static int DATE = 6;
	public final static int TIMESTAMP = 7;
	public final static int BINARY = 8;
	public final static int NOT_SUPPORT = 10;
	
	//cann't construct instance
	private ReflectParser(){}
	
	@SuppressWarnings("rawtypes")
	public static Object getValue(Object instance, String fieldName) {
		Class clazz = instance.getClass();
		Method[] methods = clazz.getMethods();
		Object[] args = null;
		try {
			for(Method m : methods) {
				if(m.getName().equalsIgnoreCase("get" + fieldName)) {
					return m.invoke(instance, args);
				}
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		
		return null;
	}
	
	public static int getType(String colType) {
		int result = NOT_SUPPORT;
		if("INTEGER".equalsIgnoreCase(colType)) {
			result = INT;
		} else if("BIGINT".equalsIgnoreCase(colType) || "long".equalsIgnoreCase(colType)) {
			result = LONG;
		} else if(colType.startsWith("VARCHAR") || colType.startsWith("varchar")) {
			result = STRING;
		} else if("CLOB".equalsIgnoreCase(colType)) {
			result = STRING;
		} else if(colType.startsWith("FLOAT") || colType.startsWith("float")) {
			result = FLOAT;
		} else if(colType.startsWith("DOUBLE") || colType.startsWith("double")) {
			result = DOUBLE;
		} else if("BLOB".equalsIgnoreCase(colType)) {
			result = BINARY;
		} else if ("DATE".equalsIgnoreCase(colType)) {
			result = DATE;
		} else if ("TIMESTAMP".equalsIgnoreCase(colType)) {
			result = TIMESTAMP;
		}
		return result;
    }
	
	@SuppressWarnings("rawtypes")
	public static void setValue(Object instance, String field, Object value) {
		if(value == null) {
			return;
		}
		Class clazz = instance.getClass();
		Method[] methods = clazz.getMethods();
		Object[] args = {value};
		for(Method m : methods) {
			if(m.getName().equalsIgnoreCase("set"+field)) {
				try {
					m.invoke(instance, args);
					return;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}
